#coding: utf-8

from cocos2d            import *
from protocol           import *
from cocos2d.extension  import CCNetwork

__tags_for_netclient__ = []
__handlers_for_netclient__ = {}

class NetClient(CCNetwork):
    def __init__(self, tag = 0):
        self.Tag = NetClient.mask_tag(tag)
        if tag not in __tags_for_netclient__:
            __tags_for_netclient__.append(tag)
        pass

    @staticmethod
    def mask_tag(tag):
        return (0x10000 | tag)

    @staticmethod
    def un_mask_tag(tag):
        return (tag ^ 0x10000)

    @staticmethod
    def create_net_client(host, port, tag, t_scene = None):
        scene = sharedDirector.getRunningScene()
        if not scene:
            scene = t_scene
        if not scene:
            return
        n = scene.getChildByTag(NetClient.mask_tag(tag))
        if n:
            return n
        n = NetClient(tag)
        n.SetRemote(host, port)
        scene.addChild(n)
        return n

    @staticmethod
    def send_to_tag(tag, pack):
        scene = sharedDirector.getRunningScene()
        if not scene:
            return False
        n = scene.getChildByTag(NetClient.mask_tag(tag))
        if not n:
            return False
        n.send(pack)
        return True

    @staticmethod
    def switch_scene(new_scene):
        scene = sharedDirector.getRunningScene()
        if not scene:
            return
        for tag in __tags_for_netclient__:
            n = scene.getChildByTag(NetClient.mask_tag(tag))
            if n:
                n.removeFromParentAndCleanup(False)
                new_scene.addChild(n)

    @staticmethod
    def register_handler(tag, tp):
        def __func(fn):
            __handlers_for_netclient__['%s-%s'%(tag, tp)] = fn
            return fn
        return __func

    def send(self, packet):
        pack = GeneralPack(packet)
        pack.SCHEMA = PacketSchema.PS_C2S
        pack.TAG    = NetClient.un_mask_tag(self.Tag)
        super(NetClient, self).send(pack)

    def on_packet_in(self, packet):
        tag = NetClient.un_mask_tag(self.Tag)
        pack = GeneralPack(packet)
        fn = __handlers_for_netclient__.get('%s-%s'%(tag, pack.TYPE))
        if not fn:
            print 'on_packet_in >>> handler for %d(%s) not found'%(pack.TYPE, tag)
        else:
            fn(pack)